package com.pnk087.servlet.chapter1;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;

/**
 * Created by IntelliJ IDEA.
 * User: khanhpham
 * Date: 2/17/12
 * Time: 5:21 AM
 * To change this template use File | Settings | File Templates.
 */
public class Ch1Servlet extends HttpServlet {
    private String threadName;
    private SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");

    public Ch1Servlet() {
        threadName = "Chapter1Servlet" + sdf.format(Calendar.getInstance().getTime());
    }

    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        super.service(req, resp);
        System.out.println("service() method invoked");
        System.out.println("Servlet Params");
        Enumeration initParamNames = this.getServletConfig().getInitParameterNames();
        while (initParamNames.hasMoreElements()) {
            String name = (String) initParamNames.nextElement();
            String value = this.getServletConfig().getInitParameter(name);
            System.out.println(name + " : " + value);
        }

        System.out.println("Context params");
        Enumeration contextParamNames = this.getServletContext().getInitParameterNames();
        while (contextParamNames.hasMoreElements()) {
            String name = (String) contextParamNames.nextElement();
            String value = this.getServletContext().getInitParameter(name);
            System.out.println(name + " : " + value);
        }
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.println("<html><body>Hello: " + threadName + "</body></html>");
        System.out.println(Thread.currentThread().getName());
    }
}
